<template>
  <div id="objLoadContainer"></div>
</template>

<script>
import * as THREE from 'three';
import {MTLLoader} from 'three/examples/jsm/loaders/MTLLoader';
import {OBJLoader} from 'three/examples/jsm/loaders/OBJLoader';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls';


export default {
  data() {
    return {
      camera: null,
      scene: null,
      renderer: null,
      controls: null,
    };
  },
  mounted() {
    this.init();
    this.animate();
  },
  methods: {
    init() {
      let container = document.getElementById("objLoadContainer");// 显示3D模型的容器
      this.camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.01, 100000000.04);
      this.camera.position.x = -55018.979;
      this.camera.position.y = 8551.089;
      this.camera.position.z = -22377.155;

      // scene
      this.scene = new THREE.Scene();

      const ambientLight = new THREE.AmbientLight(2236962, 1);
      this.scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(16777215, 1);
      this.camera.add(directionalLight);
      this.scene.add(this.camera);

      // model
      const onProgress = function (xhr) {
        if (xhr.lengthComputable) {
          const percentComplete = xhr.loaded / xhr.total * 100;
          console.log(Math.round(percentComplete, 2) + '% downloaded');
        }
      };
      new MTLLoader()
          .setPath('/load/obj/')
          .load('test1.mtl', (materials) => {
            materials.preload();
            new OBJLoader()
                .setMaterials(materials)
                .setPath('/load/obj/')
                .load('test1.obj', (object) => {
                  this.scene.add(object);
                }, onProgress);
          });
      //
      this.renderer = new THREE.WebGLRenderer();
      this.renderer.outputEncoding = THREE.sRGBEncoding;
      this.renderer.setPixelRatio(window.devicePixelRatio);
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      container.appendChild(this.renderer.domElement);
      //创建控件对象
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.enableDamping = false;
      this.controls.minDistance = 1;
      this.controls.maxDistance = Infinity;
      this.controls.enableZoom = true;
      this.controls.update();
    },
    animate() {
      requestAnimationFrame(this.animate);
      this.controls.update();
      this.renderer.render(this.scene, this.camera);
    }
  }
};
</script>

<style scoped>
* {
  margin: 0;
}

#objLoadContainer {
  position: absolute;
  width: 100%;
  height: 100%;
}
</style>
